package com.dao.c.backend.service.impl;

import com.dao.c.backend.common.CommonResult;
import com.dao.c.backend.common.MessageCode;
import com.dao.c.backend.common.StatusCode;
import com.dao.c.backend.dao.ModelMapper;
import com.dao.c.backend.entity.Model;
import com.dao.c.backend.entity.Session;
import com.dao.c.backend.dao.SessionMapper;
import com.dao.c.backend.entity.User;
import com.dao.c.backend.service.ISessionService;
import com.dao.c.backend.vo.SessionVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张幸晔
 * @since 2025-02-22
 */
@Service
public class SessionServiceImpl extends ServiceImpl<SessionMapper, Session> implements ISessionService {

    @Autowired
    private SessionMapper sessionMapper;
    @Autowired
    private ModelMapper modelMapper;



    @Override
    public CommonResult listAll(User user) {
        LambdaQueryWrapper<Session> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Session::getUid, user.getId()).eq(Session::getStatus, 1)
                .orderByDesc(Session::getCreatetime);
        List<Session> sessions = sessionMapper.selectList(lambdaQueryWrapper);
        if (sessions.isEmpty()) {
            return new CommonResult<>(StatusCode.SUCCESS, MessageCode.SELECT, null);
        }
        List<SessionVo> sessionVos = new ArrayList<>();
        for (Session session : sessions) {
            sessionVos.add(new SessionVo(session));
        }
        addModelAvatarInfo(sessionVos);
        return new CommonResult<>(StatusCode.SUCCESS, MessageCode.SELECT, sessionVos);
    }


    @Override
    public CommonResult clearAll(Session session) {
        LambdaUpdateWrapper<Session> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Session::getUid, session.getUid()).set(Session::getStatus, 0).set(Session::getUpdatetime,
                LocalDateTime.now());
        int rows = sessionMapper.update(lambdaUpdateWrapper);
        if (rows <= 0) {
            return new CommonResult<>(StatusCode.ERROR, MessageCode.UPDATEFAIL, null);
        }
        return new CommonResult<>(StatusCode.SUCCESS, MessageCode.UPDATE, rows);

    }

    @Override
    public CommonResult delete(Session session) {
        LambdaUpdateWrapper<Session> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Session::getId, session.getId()).set(Session::getStatus, 0).set(Session::getUpdatetime,
                LocalDateTime.now());
        int rows = sessionMapper.update(lambdaUpdateWrapper);
        if (rows <= 0) {
            return new CommonResult<>(StatusCode.ERROR, MessageCode.UPDATEFAIL, null);
        }
        return new CommonResult<>(StatusCode.SUCCESS, MessageCode.UPDATE, rows);
    }

    /**
     * @param sessionVos
     * @return SessionVo 会话和模型的视图
     * @description 利用session的mid去检索model信息并拼接到一起
     * @author 张幸晔
     * @date 2025-03-12 09:57
     */

    private void addModelAvatarInfo(List<SessionVo> sessionVos) {
        // 提取session中的mid，方便批量查询
        Set<Integer> modelIds = new HashSet<>();
        for (SessionVo sessionVo : sessionVos) {
            modelIds.add(sessionVo.getMid());
        }
        // 根据mid查询model表
        LambdaQueryWrapper<Model> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Model::getId, modelIds);
        List<Model> models = modelMapper.selectList(lambdaQueryWrapper);
        // 构造映射关系，方便匹配mid与avatar
        Map<Integer, String> hashMap = new HashMap<>();
        Map<Integer, String> nameMap = new HashMap<>();
        for (Model model : models) {
            hashMap.put(model.getId(), model.getAvatar());
            nameMap.put(model.getId(), model.getModelname());
        }
        // 将哈希表中的mid和sessionvo中的mid一一对应
        sessionVos.forEach(e -> {
            e.setModelAvatar(hashMap.get(e.getMid()));
            e.setModelName(nameMap.get(e.getMid()));
        });
    }

}
